package com.bsh.shiro;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.bsh.mybatis.model.Admin;
import com.bsh.service.ModuleService;

/**
 * @author gsh
 * @since 0.0.1
 */
@Component
public class UserContext {
	static UserContext mthis;
	@Autowired
    ModuleService moduleServ;

    @PostConstruct
    public void init() {  
    	mthis = this;    	
    	mthis.moduleServ = this.moduleServ; 
    } 
    
    
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return attrs.getRequest();
    }

    public static HttpSession getSession() {
        HttpSession session = null;
        try {
            session = getRequest().getSession();
        } catch (Exception e) {
        }
        return session;
    }


    /**
     * 是否已登录
     * @return
     */
    public static boolean isLogined() {
        return SecurityUtils.getSubject().isAuthenticated();
    }


    /**
     * 取得登录用户信息
     * @return
     */
    public static Admin getLoginUser() {
        return (Admin) SecurityUtils.getSubject().getPrincipal();
    }
    
    /**
     * 取得用户的菜单
     */
    public static boolean checkUserModule(String moduleId){
    	if(!isLogined())return false;
    	if("admin".equals(getLoginUser().getLoginName()))return true;
    	return SecurityUtils.getSubject().isPermitted(moduleId);
    }
    
    public static String getUserRoles(){
    	if(!isLogined())return null;
    	if("admin".equals(getLoginUser().getLoginName()))return "系统管理员";
    	
    	Session session = SecurityUtils.getSubject().getSession();   
    	Object obj= session.getAttribute("roles");
    	return obj==null?null:obj.toString();
    }
}
